package com.agent.web;

import com.agent.entity.Dept;
import com.agent.entity.Dict;
import com.agent.entity.RepaireInfo;
import com.agent.entity.User;
import com.agent.page.EasyuiPage;
import com.agent.service.IDeptService;
import com.agent.service.IDictService;
import com.agent.service.IRepaireInfoService;
import com.agent.service.UserService;
import com.agent.service.impl.RepaireInfoServiceImpl;
import com.agent.shiro.ShiroUser;
import com.agent.spring.websocket.SpringWebSocketHandler;
import com.agent.util.CommonUtils;
import com.agent.util.Constants;
import com.agent.util.DateUtil;
import com.agent.util.ResponseData;
import com.agent.vo.RepaireInfoVO;
import com.weixin.pojo.Text;
import com.weixin.pojo.Textcard;
import com.weixin.pojo.WXMsg;
import com.weixin.service.WeixinNotifyService;
import com.weixin.util.WxepConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.socket.TextMessage;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.agent.util.ResponseData.getErrorResult;
import static com.agent.util.ResponseData.getSuccessResult;

@Controller
@Slf4j
@RequestMapping(value = "/repaireInfo")
public class RepaireInfoController {

    @Resource(name = "repaireInfoService")
    IRepaireInfoService service;
    @Resource(name = "userServiceImpl")
    UserService userService;

    @Resource(name = "weixinNotifyService")
    WeixinNotifyService weixinNotifyService;

    @Resource(name = "dictService")
    IDictService dictService;

    @Autowired
    IDeptService deptService;

    @Bean
    public SpringWebSocketHandler infoHandler() {
        return new SpringWebSocketHandler();
    }

    @RequestMapping(method = RequestMethod.GET)
    public String toHtml(){
        return "callIn/repaireInfo";
    }

    @RequestMapping(value = "/toAdd")
    public String toAdd(){
        return "/soft-phone/addWorkOrder";
    }

    @RequestMapping(value = "/list",method = RequestMethod.GET)
    @ResponseBody
    public EasyuiPage list(Integer page, Integer rows, RepaireInfoVO repaireInfoVO){
        if(!StringUtils.isEmpty(repaireInfoVO.getRingTime())){
            String[] split = repaireInfoVO.getRingTime().split(" - ");
            repaireInfoVO.setBeginDate(DateUtil.parseDate(split[0],DateUtil.DATE_TIME_FORMAT));
            repaireInfoVO.setEndDate(DateUtil.parseDate(split[1],DateUtil.DATE_TIME_FORMAT));
        }
        EasyuiPage<RepaireInfo> result = service.searchRepaireInfo(page, rows, repaireInfoVO);
        return result;
    }

    @RequestMapping(value = "/export",method = RequestMethod.GET)
    @ResponseBody
    public void export(RepaireInfoVO repaireInfoVO, HttpServletResponse response){
       /* repaireInfoVO.setEmail(null);
        repaireInfoVO.setStatus(null);
        repaireInfoVO.setWorkOrderId(null);*/
        if(!StringUtils.isEmpty(repaireInfoVO.getRingTime())){
            String[] split = repaireInfoVO.getRingTime().split(" - ");
            repaireInfoVO.setBeginDate(DateUtil.parseDate(split[0],DateUtil.DATE_TIME_FORMAT));
            repaireInfoVO.setEndDate(DateUtil.parseDate(split[1],DateUtil.DATE_TIME_FORMAT));
        }
        try (Workbook sheets = service.exportExcel(repaireInfoVO);OutputStream output = response.getOutputStream();
             BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);) {
            // 判断数据
            if(sheets == null) {
                return ;
            }
            // 重置响应对象
            response.reset();
            // 当前日期，用于导出文件名称
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String fileName = "工单-"+sdf.format(new Date())+".xls";
            // 指定下载的文件名--设置响应头
            response.setHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes(),"ISO8859-1"));
//            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            sheets.write(bufferedOutPut);
        }catch (Exception e){
            log.error("export excel error| ",e);
        }
    }


    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> insert(RepaireInfoVO repaireInfoVO){
        User in = new User();
        in.setRoleId(5);
        if(!StringUtils.isEmpty(repaireInfoVO.getEmail())){
            in.setEmail(repaireInfoVO.getEmail());
        }else{
            in.setTelphone(repaireInfoVO.getCreateMobile());
        }
        try{
            List<User> userList = userService.findUser(in);
            if(userList ==null || userList.size()==0){
                return getErrorResult("该手机号对应的客户不存在，请检查！");
            }
            String userId = userList.get(0).getUserName();
            repaireInfoVO.setCreator(userId);
            service.insertByUserId(userId, repaireInfoVO);
//            RepaireInfo repaireInfo = service.getRepaireInfo(orderId + "");
//            String workOrderId = repaireInfo.getWorkOrderId();
            notifyCreator(userId);
            //  工程师微信端提醒
            /*if(repaireInfo.getStatus().equals("00")){ //只有待流转的单子 才通知坐席
                User in_2 = new User();
                in_2.setRoleId(2);  //改为提醒座席
                List<User> list = userService.findUser(in_2);
                StringBuffer sb = new StringBuffer();
                for(User u:list){
                    sb.append(u.getUserName());
                    sb.append("|");
                }
                String toUser = sb.substring(0,sb.length()-1);
                StringBuffer socketMsg = new StringBuffer("您有工单需要处理，单号："+ workOrderId +"；");
                socketMsg.append("您有工单需要处理，单号：<a href=javascript:process_00("+orderId+",00)>"+ workOrderId +"，请点击处理；");
                infoHandler().sendMessageToUsersByName(toUser,new TextMessage(socketMsg));
            }*/
        }catch (Exception e){
            log.error("com.agent.web.RepaireInfoController.insert error |",e);
            return getErrorResult("新增工单失败！");
        }

        return getSuccessResult();
    }

    private void notifyCreator(String userId) throws Exception {
        WXMsg wxMsg = new WXMsg();
        wxMsg.setAgentid(WxepConstants.REPAIRE_AGENT_ID);
        wxMsg.setMsgtype("text");
        wxMsg.setTouser(userId);
        Text text = new Text();
        Dict dict = null;
        if(DateUtil.isWorkDate()){
            dict = dictService.getDict(Constants.CREATE_MSG);
        }else{
            dict = dictService.getDict(Constants.NOWORKER_CREATE_MSG);
        }
        text.setContent(dict.getDictValue());
        wxMsg.setText(text);
        weixinNotifyService.sendMsg(wxMsg,WxepConstants.REPAIRE_SECRET);
    }
    @RequestMapping(value = "/engineer" ,method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> findEngineer(){
        User  user = new User();
        user.setEnabled(true);
        List<User> users = userService.listByAllocation(user);
        Map<String,Object> result = getSuccessResult();
        result.put(ResponseData.DATA,users);
        return result;
    }
    @RequestMapping(value = "/getRepaireinfo" ,method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> getRepaireinfo(RepaireInfo repaireInfo){
        repaireInfo = service.getRepaireInfo(repaireInfo.getId()+"");

        List<Dept> deptList = deptService.listNoPage(new Dept());

        repaireInfo.setCallerDeptName(RepaireInfoServiceImpl.coverToName(repaireInfo.getCallerDeptId(), deptList));
        Map<String,Object> result = getSuccessResult();
        repaireInfo.setAddress(Constants.addressMap.get(repaireInfo.getAddress()));
        result.put(ResponseData.DATA,repaireInfo);
        return result;
    }
    @RequestMapping(value = "/getRepaireInfoByOrderId" ,method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> getRepaireInfoByOrderId(RepaireInfo repaireInfo){
        repaireInfo = service.getRepaireInfoByOrderId(repaireInfo.getWorkOrderId()+"");

        List<Dept> deptList = deptService.listNoPage(new Dept());

        repaireInfo.setCallerDeptName(RepaireInfoServiceImpl.coverToName(repaireInfo.getCallerDeptId(), deptList));
        Map<String,Object> result = getSuccessResult();
        repaireInfo.setAddress(Constants.addressMap.get(repaireInfo.getAddress()));
        result.put(ResponseData.DATA,repaireInfo);
        return result;
    }
    @RequestMapping(value = "/circulation" ,method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> getCirculation(HttpServletRequest request){
        User  user = new User();
        user.setEnabled(true);
        List<User> users = new ArrayList<>();
        User temp1 = new User();
        temp1.setUserName("0");
        temp1.setDisplayName("抢单模式");
        users.add(0,temp1);
        User temp2 = new User();
        temp2.setUserName("1");
        temp2.setDisplayName("自动派单模式");
        users.add(1,temp2);
        Map<String,Object> result = getSuccessResult();
        result.put(ResponseData.DATA,users);

        //提醒座席
        String orderId = request.getParameter("orderId");
        if(!CommonUtils.isEmptyOrNull(orderId)) {
            User in = new User();
            in.setRoleId(2);  //改为提箱座席
            List<User> list = userService.findUser(in);
            StringBuffer sb = new StringBuffer();
            ShiroUser shiroUser = (ShiroUser)SecurityUtils.getSubject().getPrincipal();
            for (User u : list) {
                if(!u.getUserName().equals(shiroUser.getUserName())) {
                    sb.append(u.getUserName());
                    sb.append("|");
                }
            }
            String toUser = sb.substring(0, sb.length() - 1);
            String workOrderId = service.getRepaireInfo(orderId + "").getWorkOrderId();
            infoHandler().sendMessageToUsersByName(toUser, new TextMessage("订单【" + workOrderId + "】已有座席处理，请勿重复操作；"));
        }
        return result;
    }


    @RequestMapping("/endServer/{id}")
    @ResponseBody
    public Map<String,Object> endServer(@PathVariable("id") String id, Model model){
        RepaireInfo repaireInfo = new RepaireInfo();
        repaireInfo.setId(Long.parseLong(id));
        repaireInfo.setBeginProcessTime(new Date()); // 网页上点击完成  则开始时间 结束时间都为当前时间
        repaireInfo.setEndProcessTime(new Date());
        ShiroUser shiroUser = (ShiroUser)SecurityUtils.getSubject().getPrincipal();
        repaireInfo.setCurrentId(shiroUser.getUserName()); // 结束服务时 当前操作人作为工程师
        repaireInfo.setCurrentName(shiroUser.getDisplayName());
        repaireInfo.setStatus("04");
        service.update(repaireInfo);
        RepaireInfo result =service.getRepaireInfo(id);
        Dict dict = dictService.getDict(Constants.TO_CUSTOMER_SATISFACTION);
        //  微信端提醒
        WXMsg wxMsg = new WXMsg();
        wxMsg.setAgentid(WxepConstants.REPAIRE_AGENT_ID);
        wxMsg.setMsgtype("text");
        wxMsg.setTouser(result.getCreator());
        Text text = new Text();
//        text.setContent("对我们的服务还满意吗？<a href=\"http://www.xutao.cf:8080/weixin/to_customer_satisfaction/"+result.getId()+"\">给TA一个评价吧！</a>说不定有惊喜哦~");
        text.setContent(dict.getDictValue().replace("{repairId}",id));
        wxMsg.setText(text);
        try {
            weixinNotifyService.sendMsg(wxMsg,WxepConstants.REPAIRE_SECRET);
        } catch (Exception e) {
            log.error("weixinNotifyService.sendMsg error|",e);
            return ResponseData.getErrorResult("发送微信通知失败");
        }
        return ResponseData.getSuccessResult();
    }
    /**
     * 座席分配工程师
     * @param repaireInfo
     * @return
     */
    @RequestMapping(value = "/updateByCustomService" ,method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> updateByCustomService(RepaireInfo repaireInfo){
        service.update(repaireInfo);
        RepaireInfo repaireInfoResult = service.getRepaireInfo(repaireInfo.getId().toString());
        //  微信端提醒
        Dict dict = dictService.getDict(Constants.CALLER_NOTIFY_TO_CREATOR);
        String content = dict.getDictValue().replace("{expectTime}", repaireInfoResult.getExpectTime());
        String content1 = "亲爱的同事：您的IT服务时间更改为："+repaireInfoResult.getExpectTime()+"。单号："+repaireInfoResult.getWorkOrderId()+"；请注意处理！";
        WXMsg wxMsg = getWxMsg(content, repaireInfoResult.getCreator(),WxepConstants.REPAIRE_AGENT_ID);
        WXMsg wxEngMsg = getWxMsg(content1, repaireInfoResult.getCurrentId(),WxepConstants.ENGINEER_AGENT_ID);
        try {
            weixinNotifyService.sendMsg(wxMsg,WxepConstants.REPAIRE_SECRET);
            weixinNotifyService.sendMsg(wxEngMsg,WxepConstants.ENGINEER_SECRET);
        } catch (Exception e) {
            log.error("weixinNotifyService.sendMsg error|",e);
        }
        return getSuccessResult();
    }

    private WXMsg getWxMsg(String content, String user,String type) {
        WXMsg wxMsg = new WXMsg();
        wxMsg.setAgentid(type);
        wxMsg.setMsgtype("text");
        wxMsg.setTouser(user);
        Text text = new Text();
        text.setContent(content);
        wxMsg.setText(text);
        return wxMsg;
    }

    /**
     * 派单
     * 座席分配工程师
     * @param repaireInfo
     * @return
     */
    @RequestMapping(value = "/update" ,method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> update01(RepaireInfo repaireInfo){
        try{
            // 如果是IT维护组  则通知所有工程师 并将该工单状态更改为待接单  当前处理人置空
            if("group".equals(repaireInfo.getCurrentId())){
                repaireInfo.setStatus("06");
                repaireInfo.setCurrentName("");
                repaireInfo.setCurrentId("");
                service.update(repaireInfo);
                User in = new User();
                in.setRoleId(3);
                in.setRankId("1"); // 属于组
//                in.setNotNullrankId("true");
                in.setEnabled(true);
                List<User> userList = userService.list(in);
                service.notifyEngineer(userList);
            }else{ // 如果是个人 则直接更新给个人
                repaireInfo.setStatus("06");
                ShiroUser shiroUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
                repaireInfo.setAllocationer(shiroUser.getUserName()); //将调配者插入数据库
                service.update(repaireInfo);
                List<User> list = new ArrayList<>();
                User u = new User();
                u.setUserName(repaireInfo.getCurrentId());
                list.add(u);
                service.notifyEngineer(list);
            }
            return getSuccessResult();
        }catch (Exception e){
            log.error("com.agent.web.RepaireInfoController.update01 error |",e);
            return getErrorResult("派单失败");
        }
    }

    /**
     * 已经废弃  2019-7-24
     * 座席流转操作
     * @param repaireInfoVO
     * @param request
     * @return
     */
    @RequestMapping(value = "/execute/circulation" ,method = RequestMethod.POST)
    @ResponseBody
    @Deprecated
    public Map<String,Object> executeCirculation(RepaireInfoVO repaireInfoVO, HttpServletRequest request){
        String userId = service.getRepaireInfo(repaireInfoVO.getId().toString()).getCurrentId();
        try {
            User user = service.circulation(userId, repaireInfoVO, (String) request.getParameter("type"));
            notifyCreator(userId);
//            service.notifyEngineer(user);
        } catch (Exception e) {
            log.error("com.weixin.web.WXRepaireController.addWorkOrder error |",e);
            return getErrorResult("系统内部错误");
        }
        return  getSuccessResult();
    }


}
